import { drizzle } from "drizzle-orm/postgres-js"
import postgres from "postgres"
import * as schema from "./schema"

// 获取数据库连接字符串
function getDatabaseUrl() {
  // 在Nuxt服务器环境中获取配置
  if (import.meta.server) {
    return process.env.DATABASE_URL || "postgresql://localhost:5432/mindweaver"
  }
  return "postgresql://localhost:5432/mindweaver"
}

const connectionString = getDatabaseUrl()

let client: any
let db: any

try {
  client = postgres(connectionString, {
    max: 10,
    idle_timeout: 20,
    connect_timeout: 10,
  })
  db = drizzle(client, { schema })
  console.log("✅ Database connected successfully")
} catch (error) {
  console.warn("⚠️ Database connection failed, using mock database for development:", error)

  // 创建模拟数据库对象用于开发测试
  const mockUser = {
    id: 1,
    email: "test@example.com",
    name: "Test User",
    avatar: null,
    createdAt: new Date(),
    updatedAt: new Date(),
    password: "$2a$12$mockhashedpassword",
    googleId: null,
    githubId: null,
    isEmailVerified: false,
  }

  db = {
    select: () => ({
      from: (table: any) => ({
        where: (condition: any) => ({
          limit: (num: number) => Promise.resolve([mockUser]),
          orderBy: (order: any) => ({
            limit: (num: number) => Promise.resolve([mockUser]),
          }),
        }),
        limit: (num: number) => Promise.resolve([mockUser]),
        orderBy: (order: any) => ({
          limit: (num: number) => Promise.resolve([mockUser]),
        }),
      }),
    }),
    insert: (table: any) => ({
      values: (data: any) => ({
        returning: () => Promise.resolve([{ ...mockUser, ...data }]),
      }),
    }),
    update: (table: any) => ({
      set: (data: any) => ({
        where: (condition: any) => ({
          returning: () => Promise.resolve([{ ...mockUser, ...data }]),
        }),
      }),
    }),
  }
}

export { db }
